package com.hotchpotch.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.hotchpotch.R;

import junit.framework.Assert;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author yangyu
 * 功能描述：常量工具类
 */
public class MyUtil {
    private static final String TAG = "MyUtil";
    private static SimpleDateFormat sf;

    /**
     * 得到设备屏幕的宽度
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 得到设备屏幕的高度
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 得到设备的密度
     */
    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * 把密度转换为像素
     */
    public static int dip2px(Context context, float px) {
        final float scale = getScreenDensity(context);
        return (int) (px * scale + 0.5);
    }

    public static double change(double a) {
        return a * Math.PI / 180;
    }

    /**
     * 读取assets文件夹的文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String readAssert(Context context, String fileName) {
        String resultString = "";
        try {
            InputStream inputStream = context.getResources().getAssets().open(fileName);
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            resultString = new String(buffer, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    /**
     * 时间戳转换成字符窜
     */
    public static String getDateToString(long time) {
        Date d = new Date(time);
        sf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        return sf.format(d);
    }

    /**
     * 倒计时时间戳转化为时分秒格式
     *
     * @param time
     * @return
     */
    public static String countDownTimerHour(long time) {
        //得到小时
        long hour = time / 1000 / 60 / 60;
        //减去小时
        long time1 = time - (hour * 60 * 60 * 1000);
        //得到分钟数
        long minute = time1 / 1000 / 60;
        //减去分
        long time2 = time1 - (minute * 60 * 1000);
        //得到秒
        long secs = time2 / 1000;
        return hour + "小时" + minute + "分" + secs + "秒";
    }

    /**
     * 倒计时时间戳转化为时分秒格式
     *
     * @param time
     * @return
     */
    public static String countDownTimerDay(long time) {
        //得到天
        long day = time / 1000 / 60 / 60 / 24;
        //减去天得到小时
        long time1 = time - (day * 24 * 60 * 60 * 1000);
        //得到小时
        long hour = time1 / 1000 / 60 / 60;
        //减去小时
        long time2 = time1 - (hour * 60 * 60 * 1000);
        //得到分钟数
        long minute = time2 / 1000 / 60;
        //减去分
        long time3 = time2 - (minute * 60 * 1000);
        //得到秒
        long secs = time3 / 1000;
        return day + "天" + hour + "小时" + minute + "分" + secs + "秒";
    }


    /**
     * 倒计时，仅显示小时，分钟，秒
     *
     * @param time
     * @return
     */
    public static String countDownTimerHourNoDay(long time) {
        //得到天
        long day = time / 1000 / 60 / 60 / 24;
        long dayTime = day * 24 * 60 * 60 * 1000;
        //减去天得到小时
        long time1 = time - dayTime;
        //得到小时
        long hour = time1 / 1000 / 60 / 60;
        long hourTime = hour * 60 * 60 * 1000;
        //减去小时
        long time2 = time1 - hourTime;
        //得到分钟数
        long minute = time2 / 1000 / 60;
        long minTime = minute * 60 * 1000;
        //减去分
        long time3 = time2 - minTime;
        //得到秒
        long secs = time3 / 1000;
//        Logg.e(TAG, "天数 = " + day + "，小时 = " + hour + "，分钟 = " + minute + "，秒 = " + secs);
//        Logg.e(TAG, "time1 = " + time1 + "，time2 = " + time2 + "，time3 = " + time3);
        return hour + ":" + minute + ":" + secs;
    }

    /**
     * 由字符串格式的时间戳获取到相应天数
     *
     * @param starTime
     * @param endTime
     * @return
     */
    public static String getDay(String starTime, String endTime) {
        long star = Long.parseLong(starTime);
        long end = Long.parseLong(endTime);
        long differ = end - star;
        String result = String.valueOf(differ / 60 / 60 / 24);
        return result;
    }

    /**
     * 得到天数
     *
     * @param time
     * @return
     */
    public static String getDay(long time) {
        String result = String.valueOf(time / 1000 / 60 / 60 / 24);
        return result;
    }

    /**
     * 倒计时得到单独的时分秒
     *
     * @param time
     */
    public static String[] countDownTimerTextview(long time) {
        String[] results = new String[6];
        //得到天
        long day = time / 1000 / 60 / 60 / 24;
        //减去天得到小时的毫秒
        long time1 = time - (day * 24 * 60 * 60 * 1000);
        //得到小时
        long hour = time1 / 1000 / 60 / 60;
        //减去小时得到分钟数的毫秒
        long time2 = time1 - (hour * 60 * 60 * 1000);
        //得到分钟数
        long minute = time2 / 1000 / 60;
        //减去分得到秒的毫秒
        long time3 = time2 - (minute * 60 * 1000);
        //得到秒
        long secs = time3 / 1000;
        String h = hour + "";
        String m = minute + "";
        String s = secs + "";
        if (h.length() == 2) {
            results[0] = h.charAt(0) + "";
            results[1] = h.charAt(1) + "";
        } else {
            results[0] = 0 + "";
            results[1] = h;
        }
        if (m.length() == 2) {
            results[2] = m.charAt(0) + "";
            results[3] = m.charAt(1) + "";
        } else {
            results[2] = 0 + "";
            results[3] = m;
        }
        if (s.length() == 2) {
            results[4] = s.charAt(0) + "";
            results[5] = s.charAt(1) + "";
        } else {
            results[4] = 0 + "";
            results[5] = s;
        }
        return results;
    }

    /**
     * 判断字符串是否包含 http://
     *
     * @param string
     * @return
     */
    public static boolean isContainsHttp(String string) {
        if (string.contains("http:")) {
            return true;
        }
        return false;
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static byte[] getHtmlByteArray(final String url) {
        URL htmlUrl = null;
        InputStream inStream = null;
        try {
            htmlUrl = new URL(url);
            URLConnection connection = htmlUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = inputStreamToByte(inStream);

        return data;
    }

    public static byte[] inputStreamToByte(InputStream is) {
        try {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            byte imgdata[] = bytestream.toByteArray();
            bytestream.close();
            return imgdata;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static byte[] readFromFile(String fileName, int offset, int len) {
        if (fileName == null) {
            return null;
        }

        File file = new File(fileName);
        if (!file.exists()) {
            Log.i(TAG, "readFromFile: file not found");
            return null;
        }

        if (len == -1) {
            len = (int) file.length();
        }

        Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));

        if (offset < 0) {
            Log.e(TAG, "readFromFile invalid offset:" + offset);
            return null;
        }
        if (len <= 0) {
            Log.e(TAG, "readFromFile invalid len:" + len);
            return null;
        }
        if (offset + len > (int) file.length()) {
            Log.e(TAG, "readFromFile invalid file len:" + file.length());
            return null;
        }

        byte[] b = null;
        try {
            RandomAccessFile in = new RandomAccessFile(fileName, "r");
            b = new byte[len]; // 创建合适文件大小的数组
            in.seek(offset);
            in.readFully(b);
            in.close();

        } catch (Exception e) {
            Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
            e.printStackTrace();
        }
        return b;
    }

    private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;

    public static Bitmap extractThumbNail(final String path, final int height, final int width, final boolean crop) {
        Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);

        BitmapFactory.Options options = new BitmapFactory.Options();

        try {
            options.inJustDecodeBounds = true;
            Bitmap tmp = BitmapFactory.decodeFile(path, options);
            if (tmp != null) {
                tmp.recycle();
                tmp = null;
            }

            Log.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
            final double beY = options.outHeight * 1.0 / height;
            final double beX = options.outWidth * 1.0 / width;
            Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
            options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
            if (options.inSampleSize <= 1) {
                options.inSampleSize = 1;
            }

            // NOTE: out of memory error
            while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
                options.inSampleSize++;
            }

            int newHeight = height;
            int newWidth = width;
            if (crop) {
                if (beY > beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            } else {
                if (beY < beX) {
                    newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
                } else {
                    newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
                }
            }

            options.inJustDecodeBounds = false;

            Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x" + options.outHeight + ", sample=" + options.inSampleSize);
            Bitmap bm = BitmapFactory.decodeFile(path, options);
            if (bm == null) {
                Log.e(TAG, "bitmap decode failed");
                return null;
            }

            Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
            final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
            if (scale != null) {
                bm.recycle();
                bm = scale;
            }

            if (crop) {
                final Bitmap cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width, height);
                if (cropped == null) {
                    return bm;
                }

                bm.recycle();
                bm = cropped;
                Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
            }
            return bm;

        } catch (final OutOfMemoryError e) {
            Log.e(TAG, "decode bitmap failed: " + e.getMessage());
            options = null;
        }

        return null;
    }

    /**
     * 把字符串转化为时间格式
     *
     * @param type      传入的时间显示格式
     * @param timestamp
     * @return
     */
    public static String getStrYMDTime(String type, long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        Date date = new Date(timestamp * 1000);
        sdf.format(date);
        return sdf.format(date);
    }

    /**
     * 存储用户信息
     *
     * @param context
     * @param info
     */
    public static void saveUserInfo(Context context, String info) {
        SharedPreDataBase.getPreferences(context).saveStringData("user_info", info);
    }

    /**
     * 获取用户信息
     *
     * @param context
     * @return
     */
    /*public static UserInfoBean getUserInfo(Context context) {
        String info = SharedPreDataBase.getPreferences(context).getStringData("user_info");
        if (TextUtils.isEmpty(info)) {
            return null;
        } else {
            UserInfoBean bean = JsonUtil.parseJson(info, UserInfoBean.class);
            return bean;
        }
    }*/

    /**
     * 联系客服
     *
     * @param context
     */
    public static void connection_service(Context context) {
        if (isQQClientAvailable(context)) {
            String[] service_numbers = {"2154713449", "3024681494", "2462269589", "3253515398", "2955978312", "2274389624", "3406330732", "2160765606"};
            Random random = new Random();
            int service_random = random.nextInt(8);
            String qqUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + service_numbers[service_random] + "&version=1";
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(qqUrl)));
        } else {
            Toast.makeText(context, "您的手机需安装手机QQ", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 判断微信是否可用
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取活动结束的天数
     *
     * @param time 传入的结束时间
     * @return
     */
    public static String getTimeOfDay(String time) {
        long currentTime = System.currentTimeMillis();
        long endTime = Long.parseLong(time) * 1000;
        long diff = endTime - currentTime;
        if (diff >= 0) {
            long result = diff / 1000 / 60 / 60 / 24;
            return "剩余" + result + "天";
        } else {
            return "活动已结束";
        }
    }

    /**
     * 根据时间获取时间差，以xxx之前显示
     *
     * @param time
     * @return
     */
    public static String getTimeOfDiffType(String time) {
        long currentTime = System.currentTimeMillis();
        long starTime = Long.parseLong(time) * 1000;

        long diffTime = currentTime - starTime;
        long day = diffTime / 1000 / 60 / 60 / 24;
        long hour = diffTime / 1000 / 60 / 60;
        long min = diffTime / 1000 / 60;
        long secs = diffTime / 1000;
        if (day > 0) {
            return day + "天前";
        } else {
            if (hour > 0) {
                return hour + "小时前";
            } else {
                if (min > 0) {
                    return min + "分钟前";
                } else {
                    return secs + "秒前";
                }
            }
        }
    }

    /**
     * 设置图片并判定
     *
     * @param context   上下文
     * @param imageUrl  图片地址
     * @param imageView
     */
    public static void setImageUrl(Context context, String imageUrl, ImageView imageView) {
        if (TextUtils.isEmpty(imageUrl)) {
            Glide.with(context).load(R.drawable.no_image).into(imageView);
        } else {
            if (isContainsHttp(imageUrl)) {
                Glide.with(context).load(imageUrl).into(imageView);
            } else {
//                Glide.with(context).load(AppConstant.BASE_LOCAL_IMG_URL + imageUrl).into(imageView);
            }
        }
    }

    /**
     * 设置图片并判定
     *
     * @param context
     * @param imageUrl
     * @param imageView
     * @param width     图片宽度修改
     */
    public static void setImageUrl(Context context, String imageUrl, ImageView imageView, int width) {
        if (TextUtils.isEmpty(imageUrl)) {
            Glide.with(context).load(R.drawable.no_image).override(width, Target.SIZE_ORIGINAL).into(imageView);
        } else {
            if (isContainsHttp(imageUrl)) {
                Glide.with(context).load(imageUrl).override(width, Target.SIZE_ORIGINAL).into(imageView);
            } else {
//                Glide.with(context).load(AppConstant.BASE_LOCAL_IMG_URL + imageUrl).override(width, Target.SIZE_ORIGINAL).into(imageView);
            }
        }
    }

    /**
     * 判断网络类型
     *
     * @param context
     * @return
     */
    public static String getCurrentNetType(Context context) {
        String type = "";
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) {
            type = "null";
        } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            type = "wifi";
        } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
            int subType = info.getSubtype();
            if (subType == TelephonyManager.NETWORK_TYPE_CDMA || subType == TelephonyManager.NETWORK_TYPE_GPRS
                    || subType == TelephonyManager.NETWORK_TYPE_EDGE) {
                type = "2g";
            } else if (subType == TelephonyManager.NETWORK_TYPE_UMTS || subType == TelephonyManager.NETWORK_TYPE_HSDPA
                    || subType == TelephonyManager.NETWORK_TYPE_EVDO_A || subType == TelephonyManager.NETWORK_TYPE_EVDO_0
                    || subType == TelephonyManager.NETWORK_TYPE_EVDO_B) {
                type = "3g";
            } else if (subType == TelephonyManager.NETWORK_TYPE_LTE) {// LTE是3g到4g的过渡，是3.9G的全球标准
                type = "4g";
            }
        }
        return type;
    }
}
